<?php
namespace Modules\Order\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Order\Models\Order;
use Modules\Order\Http\Resources\OrderResource;
use Illuminate\Support\Facades\Mail;
use Modules\Order\Mail\OrderPost;
class OrderController extends Controller{
    public function index(Request $request){
        $order_no = $request->input('order_no');
        $trade_no = $request->input('trade_no');
        $status = $request->input('status');
        $orders=Order::when($order_no,function($query)use($order_no){
            $query->where('order_id',$order_no);
        })
        ->when($trade_no,function($query)use($trade_no){
            $query->where('trade_no',$trade_no);
        })
        ->when($status,function($query)use($status){
            $query->where('status',$status);
        })
        // ->with('user')
        ->with('orderDetail.goods')
        ->get();
        return OrderResource::collection($orders);
        
    }
    public function show($id){
        $order=Order::with('orderDetail.goods')->find($id);
        with($order);
        return new OrderResource($order);
    }
    public function post(Request $request,$id){
        $order=Order::find($id);
        $request->validate([
            'express_type'=>'required|in:SF,YT,YD',
            'express_no'=>'required',
        ],[
            'express_type.required'=>'请选择快递公司',
            'express_type.in'=>'快递公司不存在',
            'express_no.required_if'=>'请输入快递单号',
        ]);
        $order->update([
            'express_type'=>$request->input('express_type'),
            'express_no'=>$request->input('express_no'),
            'status'=>3,
        ]);
        //发送邮件
        // Mail::to($order->user->email)->send(new OrderPost($order));
        Mail::to($order->user->email)->queue(new OrderPost($order));

        return new OrderResource($order);
    }
}